package com.test.huffmanserver.service.FileServiceiml;

import com.test.huffmanserver.dto.HuffmanDto;
import com.test.huffmanserver.service.FileService;
import com.test.huffmanserver.utils.FileUtils;
import com.test.huffmanserver.utils.HuffmanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class FileServiceIml implements FileService {
    @Override
    public ResponseEntity<byte[]> unZipFile(MultipartFile file) {//将文件上传至resource文件夹，并返回路径
        if (file!=null&&!file.isEmpty())
        {
            String fileName=FileUtils.upload(file);//文件存入本地
            HuffmanUtils utils=new HuffmanUtils();

            utils.unZipFile(fileName);

            System.out.println("文件解压完成");
            return FileUtils.download(fileName,FileUtils.UnZipPath);
        }
        return null;
    }

    @Override
    public HuffmanDto zipString(String original) {
        HuffmanUtils utils=new HuffmanUtils();
        HuffmanDto dto=new HuffmanDto();
        List<Byte> list=utils.arrayToList(utils.zip(original));

        dto.setByteList(list);
        dto.setCodes(utils.getCodes());
        dto.setSpecialMap(utils.getSpecialMap());
        dto.setPreArray(utils.getPreOrder());
        dto.setCompressionRatio((original.length()-list.size())+0.0/original.length());
        System.out.println("文字压缩完成");
        return dto;
    }

    @Override
    public HuffmanDto zipFile(MultipartFile file) {
        if (file!=null&&!file.isEmpty()){
            HuffmanUtils utils=new HuffmanUtils();
            String fileName=FileUtils.upload(file);

            HuffmanDto dto=new HuffmanDto();
            utils.zipFile(fileName);
            List<Byte> list=utils.arrayToList(utils.getByteArr());

            dto.setByteList(list);
            dto.setCodes(utils.getCodes());
            dto.setSpecialMap(utils.getSpecialMap());
            dto.setPreArray(utils.getPreOrder());
            dto.setCompressionRatio((file.getSize()-list.size())+0.0/file.getSize());
            System.out.println("文件压缩完成");
            return dto;
        }
        return null;
    }

    @Override
    public String unZipString(HuffmanDto dto) {
        HuffmanUtils utils=new HuffmanUtils();
        utils.setCodes(dto.getCodes());
        utils.setSpecialMap(dto.getSpecialMap());
        utils.setByteArr(utils.listToArray(dto.getByteList()));
        System.out.println("文字解压完成");
        return utils.unZip(dto.getData());
    }

    @Override
    public ResponseEntity<byte[]> zipDownload(MultipartFile file) {
        if (file!=null&& !file.isEmpty()){
            String fileName=FileUtils.upload(file);
            HuffmanUtils utils=new HuffmanUtils();
            utils.zipFile(fileName);

            System.out.println("文件压缩完成");
            return FileUtils.download(fileName,FileUtils.ZipPath);
        }
        return null;
    }
}
